/**
 * 
 */
package billing;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Properties;

/**
 * @author Gernot
 *
 */
public class BillingServerImpl extends UnicastRemoteObject implements BillingServer {
    private static final long serialVersionUID = 1L;
    private Properties login_data;
    private BillingServerSecure secureServer; //Reference to SecureServerObject Stub
    private MessageDigest md5;
    
    protected BillingServerImpl(BillingServerSecure srv) throws RemoteException {
        super();
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e1) {
           System.out.println(e1.getMessage());
        }
        this.secureServer = srv;
        login_data = new Properties();
        try {
            login_data.load(ClassLoader.getSystemResourceAsStream("user.properties"));
        } catch (FileNotFoundException e) {
           System.out.println(e.getMessage());
        } catch (IOException e) {
           System.out.println(e.getMessage());
        }
    }


    @Override
    public BillingServerSecure login(String username, String password)
            throws RemoteException {
        if (login_data.containsKey(username)){
            md5.reset();
            md5.update(password.getBytes());
            byte[] result = md5.digest();
            StringBuilder hex_str = new StringBuilder();
            for (int i=0; i<result.length; i++) {
                hex_str.append(Integer.toHexString(0xFF & result[i]));
            }
            String pwd_md5 = hex_str.toString();
            
            if (login_data.getProperty(username).equals(pwd_md5)){
                System.out.println("Login sucessful: "+username);
                return secureServer;
            } else {
                System.out.println("Login failed: password invalid");
            }
            
        } else {
            System.out.println("Login failed: unknown user");
        }
        return null;
    }

    /**
     * MD5 testing
     * @param args
     */
    public static void main(String[] args){
        String STR_TO_HASH = "dslab2012";
        try {
            BillingServerImpl srv = new BillingServerImpl(null);
            
            srv.md5.reset();
            srv.md5.update(STR_TO_HASH.getBytes());
            byte[] result = srv.md5.digest();

            StringBuilder hex_str = new StringBuilder();
            for (int i=0; i<result.length; i++) {
                hex_str.append(Integer.toHexString(0xFF & result[i]));
            }
            System.out.println(hex_str.toString());
            
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        
    }
}
